/**
 * 用户业务操作
 */

// const validator = require('validator')
const userModel = require('../models/user-info')
const userCodes = require('../codes/user')
const jwt = require('jsonwebtoken')
const globalConfigs = require('../configs')

const user = {
   /**
   * 登录业务操作
   * @param  {object} formData 登录表单信息
   * @return {object}          登录业务操作结果
   */
   async signIn( formData ) {
    const result = {
      success: false
    }

    if (!formData || !formData.account || !formData.password) {
      result.msg = userCodes.ERROR_REQUEST_EMPTY
      return result
    }

    let resultData = await userModel.getOneByAccountAndPassword({
      'password': formData.password,
      'account': formData.account
    })
    
    if (!resultData) {
      result.msg = userCodes.FAIL_USER_NAME_OR_PASSWORD_ERROR
      return result
    }

    result.success = true
    delete resultData.password
    const token = jwt.sign(resultData, globalConfigs.secret, { expiresIn: '10h' })
    result.data = {
      token
    }

    return result
  },
  /**
   * 获取用户信息
   */
  async getUserInfo(user_info) {
    const result = {
      success: false
    }
    if (!user_info || !user_info.account) {
      result.msg = userCodes.ERROR_SYS
      return result
    }

    let resultData = await userModel.getExistOne({
      'account': user_info.account
    })

    if (!resultData) {
      result.msg = userCodes.FAIL_USER_NO_EXIST
      return result
    }
    result.success = true
    delete resultData.password
    result.data = resultData
    return result
  },

  /**
   * 创建用户
   */
  async createUser(formData) {
    console.log(formData, '-----')
  }
}

module.exports = user